package com.example.springcloud.storage.service.tcc;

import com.example.springcloud.storage.mapper.StorageMapper;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 库存 TCC 服务实现
 */
@Slf4j
@Service
public class StorageTCCServiceImpl implements StorageTCCService {

    @Autowired
    private StorageMapper storageMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void tryDeduct(Long productId, Integer count) {
        log.info("库存服务 TCC Try：冻结库存");
        log.info("全局事务 XID: {}", RootContext.getXID());
        log.info("商品ID: {}, 冻结数量: {}", productId, count);

        int result = storageMapper.freeze(productId, count);
        if (result == 0) {
            throw new RuntimeException("库存不足，无法冻结");
        }

        log.info("库存冻结成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirm(BusinessActionContext context) {
        log.info("库存服务 TCC Confirm：确认扣减库存");
        log.info("全局事务 XID: {}", context.getXid());

        Long productId = Long.valueOf(context.getActionContext("productId").toString());
        Integer count = Integer.valueOf(context.getActionContext("count").toString());

        log.info("商品ID: {}, 确认扣减数量: {}", productId, count);

        int result = storageMapper.confirmDeduct(productId, count);
        if (result == 0) {
            log.error("确认扣减失败");
            return false;
        }

        log.info("库存确认扣减成功");
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancel(BusinessActionContext context) {
        log.info("库存服务 TCC Cancel：释放冻结的库存");
        log.info("全局事务 XID: {}", context.getXid());

        Long productId = Long.valueOf(context.getActionContext("productId").toString());
        Integer count = Integer.valueOf(context.getActionContext("count").toString());

        log.info("商品ID: {}, 释放数量: {}", productId, count);

        int result = storageMapper.cancelDeduct(productId, count);
        if (result == 0) {
            log.error("释放库存失败");
            return false;
        }

        log.info("库存释放成功");
        return true;
    }
}

